using System.Collections;
using SciptableObject;
using TMPro;
using UnityEngine;
using Utilities;
using Random = UnityEngine.Random;

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb;
    private SpriteRenderer _spriteRenderer;
    private TextMeshPro text;
    public float _currentSpeed = 5;
    [SerializeField] private EggMiniPeopleSO data;
    [SerializeField] private GameObject chatbox;
    [SerializeField] private CapsuleCollider2D coll;
    
    private void Awake()
    {
        coll = GetComponent<CapsuleCollider2D>();
        rb = GetComponent<Rigidbody2D>();
        _spriteRenderer = GetComponent<SpriteRenderer>();
        text = chatbox.GetComponentInChildren<TextMeshPro>();
        if (data.list.Count != 0)
        {
            RandomSpecialPeople();
        }
    }
    
    private void FixedUpdate()
    {
        rb.velocity = new Vector2(-_currentSpeed, 0f);
    }

    private void RandomSpecialPeople()
    {
        int num = Random.Range(0, data.list.Count);
        var item = data.list[num];
        _spriteRenderer.sprite = item.skin;
        var spSize = item.skin.bounds.size;
        var spCenter = item.skin.bounds.center;
        spCenter.y += spSize.y * 0.2f;
        spSize.x -= spSize.x*0.2f;
        spSize.y -= spSize.y*0.2f;
        coll.size = spSize;
        coll.offset = spCenter;
        
        StartCoroutine(SpeakDialogues(item));
    }

    IEnumerator SpeakDialogues(EggMIniPeopleDetails item)
    {
        yield return new WaitForEndOfFrame();
        yield return new WaitForSeconds(Random.Range(2, 5));
        if (item.isHasSound)
        {
            yield return new WaitForEndOfFrame();
            yield return new WaitForEndOfFrame();
            yield return new WaitForEndOfFrame();
            EventHandler.CallPlaySoundEvent(item.soundName);
        }
        int num = Random.Range(0, item.dialogues.Count);
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        text.text = item.dialogues[num];
        chatbox.SetActive(true);
        yield return new WaitForSeconds(5);
        chatbox.SetActive(false);
    }
    
    
}
